package com.woniuxy.company5.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.company5.dto.ZhaiDto;
import com.woniuxy.company5.dto.ZhaiUserDto;
import com.woniuxy.company5.entity.UserEmp;
import com.woniuxy.company5.entity.UserEmpPosition;
import com.woniuxy.company5.entity.UserPermission;
import com.woniuxy.company5.entity.UserPosition;
import com.woniuxy.company5.service.UserEmpPositionService;
import com.woniuxy.company5.service.UserEmpService;
import com.woniuxy.company5.service.UserPermissionService;
import com.woniuxy.company5.service.UserPositionService;
import com.woniuxy.company5.util.*;
import com.woniuxy.company5.vo.EchartsVo;
import com.woniuxy.company5.vo.TreeNode;
import com.woniuxy.company5.vo.ZhaiUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import sun.java2d.pipe.AAShapePipe;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author ：fengsir
 * @date ：Created in 2022/12/6 14:16
 * @description：
 * @modified By：
 * @version: $
 */
@RestController
@RequestMapping("userEmp")
public class UserEmpController {
    @Autowired
    private UserEmpService userEmpService;
    @Autowired
    private UserPositionService userPositionService;
    @Autowired
    private UserEmpPositionService userEmpPositionService;
    @Autowired
    private OssUtil ossUtil;//引入工具类
    @Autowired
    private UserPermissionService userPermissionService;
//上传文件到阿里云
    @PostMapping("/uploadoss")
    public Result fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            String url = ossUtil.uploadFile(file); //调用OSS工具类
            return Result.ok(url);
        } catch (Exception e) {
            return Result.error("上传失败");
        }
    }
//权限
    @GetMapping("persTree/{rid}")
    public Result getPermissionTree(@PathVariable("rid") Integer rid){

        //得到系统所有权限,默认从根0开始
        List<TreeNode> treeList = userPermissionService.getPermissionByParentId(0);

        //得到当前角色所有权限
        List<Integer> checkedkeys = userPermissionService.getPermissionByRole(rid);

        return Result.ok().data("treeList",treeList).data("checkedkeys",checkedkeys);
    }

//    echart图
@GetMapping("selNum")
public Result selNum(){
    List<EchartsVo> echartsVo = userEmpService.groupByDid();
    if (echartsVo != null) {
        return Result.ok().data("echartsList",echartsVo);
    }else {
        return Result.error();
    }
}
    /**
     * 从EXCEL导入到数据库
     */
    @RequestMapping("importExcel")
    public Result importExcel(MultipartFile file, HttpServletRequest request) throws Exception{

        if (null != file && !file.isEmpty()) {
            //执行读EXCEL操作,读出的数据导入List 2:从第2行开始；0:从第A列开始；0:第0个sheet
            List<PageData> listPd = (List) ObjectExcelRead.readExcel(file.getInputStream(), 1, 0, 0);
            for (PageData pageData : listPd) {
                ZhaiDto zhaiDto = new ZhaiDto();
                zhaiDto.setName(pageData.getString("var0"));
                zhaiDto.setSex(pageData.getString("var1"));
                zhaiDto.setDate(new SimpleDateFormat("yyyy-MM-dd").parse(pageData.getString("var2")));
                zhaiDto.setTel(pageData.getString("var3"));
                zhaiDto.setAccount(pageData.getString("var4"));
                zhaiDto.setPassword(pageData.getString("var5"));
                String strId = pageData.getString("var6");
                int id=0;
                if(strId.indexOf(".")!=-1){
                    id = Integer.parseInt(strId.substring(0,strId.indexOf(".")));
                }else {
                    id = Integer.parseInt(strId);
                }
                zhaiDto.setState(id);
                zhaiDto.setAdd1(pageData.getString("var7"));
                String strDeptId = pageData.getString("var8");
                int deptId=0;
                if(strDeptId.indexOf(".")!=-1){
                    deptId = Integer.parseInt(strDeptId.substring(0,strDeptId.indexOf(".")));
                }else{
                    deptId =Integer.parseInt(strDeptId);
                }
                zhaiDto.setDeptId(deptId);
                add(zhaiDto);
            }

        }
        return Result.ok("导入成功");
    }

//数据导出
    @PostMapping("excel")
    public ModelAndView exportExcel(@RequestBody ZhaiUserDto user) {
        ModelAndView mv = new ModelAndView();
        try {
            Map<String, Object> dataMap = new HashMap<>();
            //构造列名称
            List<String> titles = new ArrayList<>();
            titles.add("用户编号"); // 1
            titles.add("姓名"); // 2
            titles.add("电话"); // 3
            titles.add("职位"); // 4
            dataMap.put("titles", titles);
            //得到被导出的数据
            List<ZhaiUserVo> varOList = userEmpService.selAll(user);
            List<PageData> varList = new ArrayList<>();
            for (ZhaiUserVo userVO : varOList) {
                PageData vpd = new PageData();
                vpd.put("var1",userVO.getId());
                vpd.put("var2",userVO.getName());
                vpd.put("var3",userVO.getTel());
                vpd.put("var4",userVO.getPname());
                varList.add(vpd);
            }
            dataMap.put("varList", varList);
            ObjectExcelView erv = new ObjectExcelView();
            mv = new ModelAndView(erv, dataMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mv;
    }
//    数据导出结束
    @PostMapping("")
    public Result add(@RequestBody ZhaiDto useremp){
        int i = userEmpService.insertSelective(useremp);
        UserEmp userto = userEmpService.selectByTel(useremp.getTel(), useremp.getName());
        UserEmpPosition userEmpPosition = new UserEmpPosition();
        userEmpPosition.setEmpId(userto.getId());
        userEmpPosition.setPositionId(useremp.getDeptId());
        userEmpPositionService.insertSelective(userEmpPosition);
        if (i > 0) {
            return Result.ok();
        }else {
            return Result.error();
        }
    }



    @GetMapping("{id}")
    public Result queryById(@PathVariable Long id){
        UserEmp userEmp = userEmpService.selectByPrimaryKey(id);
        if (userEmp != null) {
            return Result.ok().data("user",userEmp);
        }else {
            return Result.error();
        }
    }
    @PutMapping("")
    public Result update(@RequestBody ZhaiDto useremp){
        int i = userEmpService.updateByPrimaryKeySelective(useremp);
        UserEmpPosition userEmpPosition = new UserEmpPosition();
        userEmpPosition.setEmpId(useremp.getId());
        userEmpPosition.setPositionId(useremp.getDeptId());
        System.out.println("ttt"+userEmpPosition.getPositionId());
        int i1 = userEmpPositionService.updateByEmpIdSelective(userEmpPosition);
        if (i > 0) {
            return Result.ok();
        }else {
            return Result.error();
        }
    }
    @DeleteMapping("{id}")
    public Result delete(@PathVariable Long id){
        int i = userEmpService.deleteByPrimaryKey(id);
        userEmpPositionService.delUserId(id);
        if (i > 0) {
            return Result.ok();
        }else {
            return Result.error();
        }
    }

    @PostMapping("selAll")
    public Result selAll(@RequestBody ZhaiUserDto userDto){

        //- true表示需要统计总数，这样会多进行一次请求select count(0); 省略掉true参数只返回分页数据。
        PageHelper.startPage(userDto.getCurrentPage(),userDto.getPageSize(),true);
        List<ZhaiUserVo> userEmps = userEmpService.selAll(userDto);
        PageInfo<ZhaiUserVo> pageInfo = new PageInfo<>(userEmps);
        //Long total = pageInfo.getTotal();得到总条数
        return Result.ok().data("userList",userEmps).data("total",pageInfo.getTotal());
    }

    @GetMapping("selAllByPosition")
    public Result toAllByPosition(){
        List<UserPosition> userPositions = userPositionService.selAllPosition();
        return Result.ok().data("positoinList",userPositions);
    }

}
